<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/12/21
 * Time: 14:47
 */
namespace App\Http\Controllers\Api;

use App\Service\Api\PromoterService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Constant\ErrorConstant;

class PromoterController extends BaseController
{
    protected $service;

    public function __construct(Request $request, PromoterService $service)
    {
        parent::__construct($request);

        $this->service  =   $service;
    }

    /**
     * 发送短信验证码
     * @return \Illuminate\Http\JsonResponse
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function codePromoter()
    {
        $validator  =   Validator::make($this->request->post(), [
            'phone'     =>  'required|regex:/^1[345789][0-9]{9}$/'
        ], [
            'phone.required'   =>  '手机号码不能为空',
            'phone.regex'      =>  '手机号格式错误'
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::API_PROMOTER_CODE_ERROR, $validator->errors()->first());
        }

        [$flag, $result]    =   $this->service->promoterCode($this->request->post('phone'));
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_PROMOTER_CODE_ERROR, $result);
        }
    }

    /**
     * 申请推广员
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirmPromoter()
    {
        $validator  =   Validator::make($this->request->post(), [
            'phone'     =>  'required|regex:/^1[345789][0-9]{9}$/',
            'check_code'=>  'required|string',
            'real_name' =>  'required|string',
            'wechat'    =>  'string'
        ], [
            'phone.required'    =>  '手机号码不能为空',
            'phone.regex'       =>  '手机号格式错误',
            'check_code.required' =>  '验证码不能为空',
            'check_code.string'   =>  '验证码必须为字符',
            'real_name.required'  =>  '姓名不能为空',
            'real_name.string'    =>  '姓名为字符',
            'wechat.string'       =>  '微信号必须为字符',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::API_PROMOTER_CONFIRM_ERROR, $validator->errors()->first());
        }

        [$flag, $result]    =   $this->service->promoterConfirm($this->request->post());
        if ($flag) {
            return $this->successResponse($result);
        } else {
            return $this->errorResponse(ErrorConstant::API_PROMOTER_CONFIRM_ERROR, $result);
        }
    }
}
